<template>
	<u-upload ref="ossUpload" :file-list="ossList" :source-type="['camera', 'album']" previewFullImage
		:max-count="maxCount" @afterRead="handleAfterRead" @delete="handleDelete" :width="width" :height="height"
		:multiple="multiple">
	</u-upload>
</template>

<script>
	import {
		uploadAliOssFile
	} from "@/oss/aliUpload.js";

	export default {
		name: "OssUploadComponent",
		props: {
			width: {
				type: [String, Number],
				default: "auto",
			},
			height: {
				type: [String, Number],
				default: "auto",
			},
			multiple: {
				type: Boolean,
				default: false,
			},
			maxCount: {
				type: Number,
				default: 1, // 设置默认支持 1 个文件
			},
		},
		data() {
			return {
				ossList: [], // 已上传文件列表
			};
		},
		methods: {
			// 删除图片
			handleDelete(event) {
				const index = this.ossList.findIndex((item) => item.url === event.file.url);
				if (index !== -1) {
					this.ossList.splice(index, 1);
					this.ossList = [...this.ossList]; // 触发响应式更新
					this.$emit("update:ossList", this.ossList); // 返回更新后的 ossList
				}
			},

			// 处理文件上传
			async handleAfterRead(event) {
				const files = Array.isArray(event.file) ? event.file : [event.file];
				const promises = files.map((file) => this.uploadSingleFile(file));
				try {
					await Promise.all(promises);
					this.$modal.msgSuccess("所有文件上传成功");
				} catch (error) {
					this.$modal.msgError("部分文件上传失败，请重试");
					console.error("上传失败:", error);
				}
				this.$emit("update:ossList", this.ossList); // 返回更新后的 ossList
			},

			// 上传单个文件
			async uploadSingleFile(file) {
				return new Promise((resolve, reject) => {
					const uploadTask = uploadAliOssFile(
						file.url,
						(res) => {
							// 添加到 ossList
							this.ossList.push({
								url: res
							});
							resolve();
						},
						(err) => reject(err)
					);
					// 监听上传进度
					uploadTask.onProgressUpdate((progress) => {
						if (progress.progress > 0 && progress.progress < 100) {
							this.$modal.loading(`上传进度: ${progress.progress}%`);
						}
					});
				});
			},
		},
	};
</script>

<style scoped>
</style>